package me.nibo.webframework.web;

import me.nibo.webframework.commons.CaptchaUtils;
import net.coding.chenxiaobo.shiro.filter.CaptchaAuthenticationFilter;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Date;


/**
 * 系统公共Controller
 */
@Controller
public class SystemCommonController {

    private static final Logger LOGGER = LoggerFactory.getLogger(SystemCommonController.class);

    /**
     * 登录方法签名
     *
     * @return 响应页面:WEB-INF/pages/login.ftl
     */
    @RequestMapping("login")
    public String login() {
        Subject subject = SecurityUtils.getSubject();
        if (subject == null || subject.isAuthenticated()) {
            return "redirect:/logout";
        }
        return "login";
    }

    /**
     * 跳转到首页
     *
     * @return 响应页面:WEB-INF/pages/home.ftl
     */
    @RequestMapping(value = {"/"})
    public String index() {
        LOGGER.debug("跳转到首页");
        return "home";
    }

    /**
     * 生成验证码方法签名
     *
     * @return 验证码图片的 byte 数组
     * @throws IOException
     */
    @RequestMapping("get-captcha")
    public ResponseEntity<byte[]> getCaptcha() throws IOException {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.IMAGE_JPEG);

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        String captcha = CaptchaUtils.getCaptcha(70, 32, 4, outputStream).toLowerCase();

        Session s = SecurityUtils.getSubject().getSession();

        s.setAttribute(CaptchaAuthenticationFilter.DEFAULT_CAPTCHA_PARAM, captcha);
        s.setAttribute(
                CaptchaAuthenticationFilter.DEFAULT_SESSION_CAPTCHA_TIMEOUT_KEY_ATTRIBUTE_NAME,
                new Date());

        byte[] bs = outputStream.toByteArray();
        outputStream.close();
        return new ResponseEntity<>(bs, headers, HttpStatus.OK);
    }
}
